package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"strings"

	"googee/common/errorx"
	"googee/common/tool"
	"googee/service/addrbook/api/internal/svc"
	"googee/service/addrbook/api/internal/types"
	"googee/service/addrbook/rpc/addrbook"

	"github.com/jinzhu/copier"
	"github.com/ppmoon/gbt2260"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateLogic) Create(req *types.CreateReq) (resp *types.BookReply, err error) {
	resp = &types.BookReply{}

	id, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, err
	}

	//TODO:检查手机格式是否正确
	if !tool.VerifyMobileFormat(req.Phone) {
		return nil, errorx.NewCodeErrorNoMsg(errorx.ADDRBOOK_ERROR + 3)
	}

	//TODO:检查区号是否正确
	region := gbt2260.NewGBT2260()
	codes := region.SearchGBT2260(fmt.Sprintf("%v", req.AdCode))
	logx.Infof("codes=%v\n", strings.Join(codes, ", "))
	if len(codes) < 3 {
		return nil, errorx.NewCodeErrorNoMsg(errorx.ADDRBOOK_ERROR + 4)
	}

	result, err := l.svcCtx.AddrBook.CreateAddrBook(l.ctx, &addrbook.CreateAddrRequest{
		UserId:    id,
		AdCode:    int64(req.AdCode),
		Phone:     req.Phone,
		Street:    req.Street,
		IsDefault: int64(req.IsDefault),
	})
	if err != nil {
		return nil, errorx.NewCodeErrorNoMsg(errorx.ADDRBOOK_ERROR + 2)
	}

	copier.Copy(&resp.Data, result)

	return
}
